import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/detail/lock_detail_notifier.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

class AddFingerprintOperation extends StatefulWidget {
  final Map info;
  final Map params;
  const AddFingerprintOperation({super.key, required this.info, required this.params});

  @override
  State<StatefulWidget> createState() => _AddFingerprintOperationState();
}

class _AddFingerprintOperationState extends State<AddFingerprintOperation> {
  Map _info = {};
  int _step = 0;
  int _totalStep = 0;
  int _connected = 1; // 1: 连接中, 2: 添加中, 3: 连接失败, 4: 添加成功
  String _fingerprintNumber = "";
  String _statusText = "正在连接设备...";

  void _addFingerprint() {
    int startDate = widget.params["startDate"] != null 
        ? DateTime.parse(widget.params["startDate"]).millisecondsSinceEpoch 
        : 0;
    int endDate = widget.params["startDate"] != null 
        ? DateTime.parse(widget.params["endDate"]).millisecondsSinceEpoch 
        : 0;

    TTLock.addFingerprint(
      null,
      startDate,
      endDate,
      _info["lockData"],
      (currentCount, totalCount) {
        setState(() {
          _totalStep = totalCount;
          _step = currentCount;
          _connected = 2;
          _statusText = "请按照提示录入指纹";
        });
      },
      (fingerprintNumber) {
        setState(() {
          _fingerprintNumber = fingerprintNumber;
          _connected = 4;
          _statusText = "指纹录入成功！";
        });
        
        Map<String, dynamic> data = {
          ...widget.params,
          "startDate": startDate,
          "endDate": endDate,
          "lockId": widget.info["lockId"],
          "fingerprintType": 1,
          "fingerprintNumber": fingerprintNumber,
        };
        _uploadFingerprint(data);
      },
      (errorCode, errorMsg) {
        setState(() {
          _connected = 3;
          _statusText = "连接设备失败，请重试";
        });
        EasyLoading.showError("$errorCode, $errorMsg");
      });
  }

  Widget _buildProgressIndicator() {
    if (_connected == 1) {
      return const CircularProgressIndicator();
    } else if (_connected == 2) {
      return CircularProgressIndicator(
        value: _totalStep > 0 ? _step / _totalStep : 0,
        backgroundColor: Colors.grey[200],
        valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
      );
    } else if (_connected == 3) {
      return Icon(Icons.error_outline, color: Colors.red, size: 60);
    } else {
      return Icon(Icons.check_circle_outline, color: Colors.green, size: 60);
    }
  }

  Widget _buildStepIndicator() {
    return Column(
      children: [
        Text(
          "$_step/$_totalStep",
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: Theme.of(context).primaryColor,
          ),
        ),
        const SizedBox(height: 8),
        LinearProgressIndicator(
          value: _totalStep > 0 ? _step / _totalStep : 0,
          backgroundColor: Colors.grey[200],
          valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
        ),
      ],
    );
  }

  Widget _buildInstructions() {
    return Container(
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.symmetric(horizontal: 24),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Text(
            _statusText,
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
            textAlign: TextAlign.center,
          ),
          if (_connected == 2) ...[
            const SizedBox(height: 16),
            Text(
              "请将手指放在指纹识别区域，\n按照提示完成指纹录入",
              style: TextStyle(fontSize: 16, color: Colors.grey[600]),
              textAlign: TextAlign.center,
            ),
          ],
        ],
      ),
    );
  }

  void _uploadFingerprint(Map<String, dynamic> data) async {
    try {
      await lockApi.uploadFingerprint(data);
      EasyLoading.showSuccess("指纹添加成功");
      Future.delayed(Duration(seconds: 1), () {
        Stacker.popUntil(ModalRoute.withName(Keys.DEVICE_LOCK_FINGERPRINT));
      });
    } catch (e) {
      EasyLoading.showError("上传指纹信息失败");
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      _info = widget.info;
    });
    _addFingerprint();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "添加指纹",
      child: Column(
        children: [
          Expanded(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildProgressIndicator(),
                  const SizedBox(height: 32),
                  if (_connected == 2) _buildStepIndicator(),
                  const SizedBox(height: 32),
                  _buildInstructions(),
                ],
              ),
            ),
          ),
          if (_connected == 3)
            Padding(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              child: Button(
                onPressed: () {
                  setState(() {
                    _connected = 1;
                    _statusText = "正在重新连接设备...";
                  });
                  _addFingerprint();
                },
                child: const Text("重试"),
              ),
            ),
        ],
      ),
    );
  }
}